'use strict';

const _ = require('underscore')
const AV = require('leanengine')
const wxAv = require('./wx-av')
const oauthCli = require('./oauth')
const WECHAT_CONFIG = require('./config')
const rp = require('request-promise')

module.exports = function (data, api) {

  var sendText = function (arg) {
    arg = _.isFunction(arg) ? arg() : arg
    api.sendText(data.FromUserName, arg, function () {
      console.log(arguments)
    })
  }

  var sendNews = function (arg) {
    arg = _.isFunction(arg) ? arg() : arg
    api.sendNews(data.FromUserName, arg, function () {
      console.log(arguments)
    })
  }

  var eventObj = {
    'location': {
      // replyType: 'text',
      // reply () {
      //   return `Latitude: ${data.Latitude}\nLongitude: ${data.Longitude}\nPrecision: ${data.Precision}`
      // }
      method () {
        // AV.login
        return
      }
    },
    'subscribe': {
      replyType: 'text',
      reply: `欢迎关注萄园红酒\n我们今天联合“乐百氏水行”共同举行第一届“乐百氏杯”羽毛球团体友谊邀请赛\n我们会在每场比赛结束后进行一次有奖竞答活动，你可以通过下方“抽奖活动”中选择你的选项参与互动答题\n我们的奖品有：乐百氏提供的厨房6件套、天堂伞、水杯，以及萄园红酒提供的海马刀、大瓶进口原装葡萄酒\n希望你能享受今天的羽毛球赛\n`,
      method () {
      }
    },
    'unsubscribe': {
      method () {
        console.log(`${data.FromUserName}取消关注了`)
      }
    },
    'view': {
      method () {
        console.log('view')
      }
    },
    'click': {
      method () {
        switch (data.EventKey) {
          case 'about':
            sendText(`Birdie卷土归来\nby GrePuG`)
            break
          case 'register-date':
            wxAv.getByOpenid(data.FromUserName).then(function (ret) {
              sendText(ret.createdAt)
            }).catch(function (err) {
              console.log(err)
            })
            break
          case 'act_a':
          case 'act_b':
          case 'act_c':
          case 'act_d':
            var reply = data.EventKey.slice(-1)
            const uri = 'https://birdie-activity.wilddogio.com'
            rp(uri + '/currentIndex.json')
            .then(ret => {
              ret = JSON.parse(ret)
              this.currentIndex = ret
              if (!ret && ret !== 0) return Promise.reject()
              return rp(uri + `/activity/${ret}.json`)
            }).then(ret => {
              ret = JSON.parse(ret)
              var result = _.map(ret.all, x => x).indexOf(data.FromUserName)
              if (ret.state === 'ongoing' && result === -1) {
                api.getUser(data.FromUserName, (err, ret) => {
                  console.log(ret)
                  ret.answer = reply
                  return rp({
                    method: 'PATCH',
                    uri: uri + `/activity/${this.currentIndex}/answers.json`,
                    body: JSON.stringify({
                      [ret.openid]: ret
                    })
                  }).then(() => {
                    return rp({
                      method: 'POST',
                      uri: uri + `/activity/${this.currentIndex}/all.json`,
                      body: data.FromUserName
                    })
                  }).then(() => {
                    return sendText(`您已提交第${this.currentIndex+1}题，您的选项是${reply.toUpperCase()}`)
                  })
                })
              } else {
                return sendText('请勿重复提交')
              }
            })
            break
          default:
            break
        }
      }
    }
  }

  var e = eventObj[data.Event.toLowerCase()]

  switch (e.replyType) {
    case 'text':
      sendText(e.reply)
      e.method && e.method()
      break
    case 'news':
      sendNews(e.reply)
      e.method && e.method()
    default:
      e.method()
      break
  }

}
